package com.pansoft.openplanet.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.EscrowAccountListBean;
import com.pansoft.openplanet.bean.EscrowRecordListBean;
import com.pansoft.openplanet.util.TCMathUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 代管账户充值 提币记录列表
 */
public class EscrowRecordListFragment extends BaseFragment {

    public static final String TAG = "EscrowRecordListFragment";
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private EscrowRecordListAdapter adapter;
    private List<EscrowRecordListBean.TrusteeshipTransactionListsBean> data = new ArrayList<>();
    private int page = 1;
    private TextView tvNoData;
    // type   类型1全部记录2充值3提币4其他
    private int type;
    private EscrowAccountListBean.AssetsBean assetsBean;


    public EscrowRecordListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_escrow_record_list, container, false);
        initView(rootView);
        initData();
        return rootView;
    }


    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        tvNoData = rootView.findViewById(R.id.tv_no_data);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                page = 1;
                data.clear();
                adapter.notifyDataSetChanged();
                loadData(false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                loadData(true);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EFHttpRequest.cancelRequest(TAG);
    }

    private void initData() {
        if (getArguments() != null && getArguments().containsKey("type")) {
            type = getArguments().getInt("type");
        }
        assetsBean = (EscrowAccountListBean.AssetsBean) getActivity().getIntent().getSerializableExtra("assetsBean");

        adapter = new EscrowRecordListAdapter(getContext(), R.layout.open_planet_item_escrow_record_list, data);
        recyclerView.setAdapter(adapter);
        refreshLayout.autoRefresh();
    }

    //加载数据
    private void loadData(final boolean isLoadMore) {
        final HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("pagesize", "10");
        map.put("type", type + "");
        map.put("page", page + "");
        map.put("trusteeshipCoinId", assetsBean.getTrusteeshipId() + "");
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/txlist", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                refreshLayout.finishRefresh(100);
                refreshLayout.finishLoadMore(100);
                try {

                    EscrowRecordListBean escrowRecordListBean = new Gson().fromJson(response, EscrowRecordListBean.class);
                    if (escrowRecordListBean == null) {
                        ToastUtils.showShort(R.string.common_text_http_request_fail);
                        return;
                    }
                    if ("success".equals(escrowRecordListBean.getResult())) {
                        data.addAll(escrowRecordListBean.getTrusteeshipTransactionLists());
                        adapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showShort(R.string.common_text_http_request_fail);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    refreshLayout.finishRefresh(100);
                    refreshLayout.finishLoadMore(100);

                    ToastUtils.showShort(R.string.common_text_http_request_fail);
                }
            }

            @Override
            public void onFail(String error) {
                refreshLayout.finishRefresh(100);
                refreshLayout.finishLoadMore(100);
                ToastUtils.showShort(R.string.common_text_http_request_fail);

            }
        });

    }

    //结束刷新
    private void finishRefresh(boolean isLoadMore) {
        if (isLoadMore) {
            refreshLayout.finishLoadMore(100);
        } else {
            refreshLayout.finishRefresh(100);
        }
    }

    public class EscrowRecordListAdapter extends CommonAdapter<EscrowRecordListBean.TrusteeshipTransactionListsBean> {

        public EscrowRecordListAdapter(Context context, int layoutId, List<EscrowRecordListBean.TrusteeshipTransactionListsBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(com.efounder.recycleviewhelper.base.ViewHolder holder, final EscrowRecordListBean.TrusteeshipTransactionListsBean item, int position) {
            ImageView ivIcon;
            TextView tvAddress;
            TextView tvTime;
            TextView tvAmount;
            TextView tvState;

            ivIcon = (ImageView) holder.getView(R.id.iv_icon);
            tvAddress = (TextView) holder.getView(R.id.tv_address);
            tvTime = (TextView) holder.getView(R.id.tv_time);
            tvAmount = (TextView) holder.getView(R.id.tv_amount);
            tvState = (TextView) holder.getView(R.id.tv_state);
            //type 1收红包 2发红包 3红包退回 4 充值 5.提现 6.兑换
            if (item.getType() == 1) {
                tvAddress.setText(R.string.open_planet_receive_red_packet);
                ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.asset_records_redpacket));
            } else if (item.getType() == 2) {
                tvAddress.setText(ResStringUtil.getString(R.string.open_planet_send_red_packet));
                ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.asset_records_redpacket));
            } else if (item.getType() == 3) {
                tvAddress.setText(R.string.open_planet_return_red_packet);
                ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.asset_records_redpacket));
            } else if (item.getType() == 4) {
                tvAddress.setText(ResStringUtil.getString(R.string.open_planet_charge));
                ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.asset_records_recharge));
            } else if (item.getType() == 5) {
                tvAddress.setText(R.string.open_planet_asset_escrow_account_withdraw);
                ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.asset_records_withdraw));
            } else if (item.getType() == 6) {
                tvAddress.setText(R.string.open_planet_exchange);
                ivIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.asset_records_withdraw));
            }
            tvTime.setText(item.getTimestamp());
            tvAmount.setText(TCMathUtil.retainAsignDecimals(Double.valueOf(item.getCoin()), 5));
            tvState.setText(R.string.common_text_confirmed);
        }
    }
}
